package nat;

import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author : zx
 * @version V1.0
 * 处理客户端连接 保存公网 内网 ip 端口二元组，转发ip信息
 */

public class NatTcpServerThread implements Runnable {

    private ServerSocket socket;
    private boolean isAlive = false;

    public NatTcpServerThread(ServerSocket socket){
        this.socket = socket;
        this.isAlive = true;
    }

    public NatTcpServerThread() throws IOException {
        this.socket = new ServerSocket(10010);
        this.isAlive = true;
    }

    public void run() {
        while (isAlive) {
            try {
                Socket listenSocket = this.socket.accept();

            } catch (Exception e) {
                this.isAlive = false;
            }
        }
    }

    public void addIpMesssage(PCBackMessage m){


    }

    class ServerListenThread implements Runnable {

        private Socket acceptSocket;

        public ServerListenThread(Socket acceptSocket){
            this.acceptSocket = acceptSocket;
        }

        public void run() {
            InputStream is;
            try {
                is = this.acceptSocket.getInputStream();
                byte[] tmp = new byte[4];
                int i = is.read(tmp);
                int length;
                PCBackMessage m;
                if (i != 4){
                    throw new IOException("length of is.read != 4.");
                }else {
                    length = ByteIntegerTool.bytes2int(tmp);
                }
                is = this.acceptSocket.getInputStream();
                tmp = new byte[length];
                i = is.read(tmp);
                if (i != length){
                    throw new IOException("length of is.read "+i+" != length " + length);
                }else {
                    m = JSONObject.parseObject(tmp, PCBackMessage.class);
                    System.out.println(m);

                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}
